package main

import (
	"github.com/kataras/iris/v12"
	"log"
	"time"
	"xorm.io/xorm"
)

// GetSopTasks 返回SOP任务列表
func GetSopTasks(ctx iris.Context) {
	var request SopTaskRequest
	if err := ctx.ReadJSON(&request); err != nil {
		ctx.JSON(Fail(err))
		return
	}

	var sopTasks []SopTask
	err := engine.Find(&sopTasks)
	if err != nil {
		ctx.JSON(Fail(err))
		return
	}
	if err != nil {
		ctx.JSON(Fail(err))
		return
	}
	ctx.JSON(sopTasks)
}

// CreateSopTask 创建SOP任务
func CreateSopTask(ctx iris.Context) {
	var sopTask SopTask
	if err := ctx.ReadJSON(&sopTask); err != nil {
		ctx.JSON(Fail(err))
		return
	}

	// 根据执行人查询出所有的需要推送的群（未解散）
	performerGroups := getPerformerGroups(&sopTask.Performers)

	// 给执行人增加代办事项
	session := engine.NewSession()
	if err := session.Begin(); err != nil {
		log.Fatalln(err)
	}

	task, err := addSopTask(session, &sopTask)
	fatal(session, err)
	println(task)

	items, err := addSopTaskItems(session, &sopTask, performerGroups)
	fatal(session, err)
	println(items)

	if err := session.Commit(); err != nil {
		log.Fatalln(err)
	}
	ctx.JSON(Success(nil))
}

func fatal(session *xorm.Session, err error) {
	if err != nil {
		if err := session.Rollback(); err != nil {
			return
		}
		log.Fatalln(err)
	}
}

func getPerformerGroups(performers *[]Performer) *[]PerformerGroups {
	log.Println(performers)

	var userIds []string
	for i, performer := range *performers {
		userIds[i] = performer.Id
	}

	var groupMembers []GroupUser
	err := engine.In("user_id", userIds).Find(&groupMembers)
	if err != nil {
		log.Fatalln(err)
	}

	var pgs []PerformerGroups
	for i, performer := range *performers {
		err := engine.Where("user_id = ?", performer.Id).Find(&groupMembers)
		if err != nil {
			log.Fatalln(err)
		}

		var groups []Group
		err = engine.In("chat_id", getChatIds(&groupMembers)).Find(&groups)
		if err != nil {
			log.Fatalln(err)
		}

		pgs[i].Performer = &performer
		pgs[i].Groups = &groups
	}
	return &pgs
}

func getChatIds(groupMembers *[]GroupUser) []string {
	var chatIds []string
	for i, gm := range *groupMembers {
		chatIds[i] = gm.ChatId
	}
	return chatIds
}

func addSopTask(session *xorm.Session, sopTask *SopTask) (int64, error) {
	return session.Insert(sopTask)
}

func addSopTaskItems(session *xorm.Session, sopTask *SopTask, performerGroups *[]PerformerGroups) (int64, error) {
	todoItems := buildSopTaskItems(sopTask, performerGroups)
	return session.Insert(todoItems)
}

func buildSopTaskItems(sopTask *SopTask, pgs *[]PerformerGroups) *[]SopTaskItem {
	var items []SopTaskItem
	for i, pg := range *pgs {
		for j, group := range *pg.Groups {
			var item SopTaskItem
			item.SopTaskId = sopTask.Id
			item.ChatId = group.ChatId
			item.UserId = pg.Performer.Id
			item.Status = 0
			items[i*j+j] = item
		}
	}
	return &items

}

// SopTaskRequest SopTask任务列表请求
type SopTaskRequest struct {
	Page int `json:"page"`
	Size int `json:"size"`
}

// SopTask 任务
type SopTask struct {
	Id       int64  `xorm:"pk autoincr comment('ID')"`
	ParentId string `json:"parentId" xorm:"bigint comment('父ID')"`
	Type     string `json:"type" binding:"required" xorm:"varchar(10) comment('任务类型')"`

	AreaId     string      `json:"areaId" xorm:"varchar(10) comment('区域ID')"`
	AreaName   string      `json:"areaName" xorm:"varchar(50) comment('区域名称')"`
	Performers []Performer `json:"performers" xorm:"-"`
	StartTime  time.Time   `json:"startTime" time_format:"2006-01-02 15:04:05" xorm:"comment('任务开始时间')"`
	EndTime    time.Time   `json:"endTime" time_format:"2006-01-02 15:04:05" xorm:"comment('任务结束时间')"`
	Created    time.Time   `xorm:"created default(CURRENT_TIMESTAMP) comment('创建时间')" time_format:"2006-01-02 15:04:05"`
	Updated    time.Time   `xorm:"updated default(CURRENT_TIMESTAMP) comment('最后更新时间')" time_format:"2006-01-02 15:04:05"`
}

// SopTaskItem SOP任务明细
type SopTaskItem struct {
	Id        int64     `xorm:"pk autoincr comment('ID')"`
	SopTaskId int64     `xorm:"comment('任务ID')"`
	UserId    string    `xorm:"varchar(50) comment('群成员ID')"`
	ChatId    string    `xorm:"varchar(50) comment('企微群ID')"`
	Status    int       `xorm:"comment('状态，0 - 未发送，1 - 已发送')"`
	Created   time.Time `xorm:"created default(CURRENT_TIMESTAMP) comment('创建时间')" time_format:"2006-01-02 15:04:05"`
	Updated   time.Time `xorm:"updated default(CURRENT_TIMESTAMP) comment('最后更新时间')" time_format:"2006-01-02 15:04:05"`
}

// Performer 执行人
type Performer struct {
	Id   string `json:"id" binding:"required"`
	Name string `json:"name" binding:"required"`
}

// PerformerGroups 执行人与群的关系
type PerformerGroups struct {
	Performer *Performer
	Groups    *[]Group
}
